package com.example.farmer.Database;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.farmer.Entity.CirclePost;

import java.util.ArrayList;
import java.util.List;

public class CircleChooseDatabase extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "farmer_circle_choose.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "circle_choose";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_CONTENT = "content";
    private static final String COLUMN_IMAGE_URL = "image_url";
    private static final String COLUMN_NUMBER = "userNumber";

    private static final String CREATE_TABLE = "CREATE TABLE "
            + TABLE_NAME + "("
            + COLUMN_ID  + "TEXT INTEGER PRIMARY KEY AUTOINCREMENT,"
            + COLUMN_CONTENT + " TEXT,"
            + COLUMN_IMAGE_URL + " TEXT ,"
            +  COLUMN_NUMBER+ " TEXT"
            + " )";

    private static CircleChooseDatabase instance;

    public CircleChooseDatabase(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public static synchronized CircleChooseDatabase getInstance(Context context) {
        if (instance == null) {
            instance = new CircleChooseDatabase(context);
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }


    public long insertPost(String userNumber,String content,String imageUrl) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_NUMBER,userNumber);
        values.put(COLUMN_CONTENT, content);
        values.put(COLUMN_IMAGE_URL,imageUrl);

        long postId = db.insert(TABLE_NAME, null, values);
        return postId;        }

    @SuppressLint("Range")
    public List<CirclePost> getAllPosts() {
        List<CirclePost> circlePostList = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);

        if (cursor.moveToFirst()) {
            do {
                CirclePost circlePost = new CirclePost();
//                circlePost.setId(cursor.getInt(cursor.getColumnIndex(COLUMN_ID)));
                circlePost.setUserNumber(cursor.getString(cursor.getColumnIndex(COLUMN_NUMBER)));
                circlePost.setContent(cursor.getString(cursor.getColumnIndex(COLUMN_CONTENT)));
                // 如果有图片URL，也添加到Post对象
                circlePost.setImageUrl(cursor.getString(cursor.getColumnIndex(COLUMN_IMAGE_URL)));
                circlePostList.add(circlePost);

            } while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return circlePostList;
    }

    // 删除帖子的方法
    public void deletePost(String userNumber) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_NAME, COLUMN_NUMBER + " = ?", new String[]{String.valueOf(userNumber)});
    }

    // 添加关注
    public long addChoose(String userNumber, String content) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_NUMBER, userNumber);
        values.put(COLUMN_CONTENT, content);
//        values.put(COLUMN_IMAGE_URL, imageUrl);
        return db.insert(TABLE_NAME, null, values); // 返回新插入行的ID或-1（如果插入失败）
    }

    // 检查是否已关注
    public boolean isChooseNumber(String userNumber) {
        SQLiteDatabase db = this.getReadableDatabase();
        String[] columns = {COLUMN_NUMBER};
        String selection = COLUMN_NUMBER + " = ?";
        String[] selectionArgs = {userNumber};
        Cursor cursor = db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, null);
        try {
            return cursor.getCount() > 0;
        } finally {
            cursor.close();
        }
    }

    // 根据用户号码查询content和image_url
    public String[] getColumnInfoByUserNumber(String userNumber) {
        String[] columns = {COLUMN_CONTENT, COLUMN_IMAGE_URL};
        String selection = COLUMN_NUMBER + " = ?";
        String[] selectionArgs = {userNumber};
        String[] result = {null, null};  // 存储查询结果

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, null);
        try {
            if (cursor.moveToFirst()) {
                result[0] = cursor.getString(0);  // 索引0对应content
                result[1] = cursor.getString(1);  // 索引1对应image_url
            }
        } catch (Exception e) {
            // 异常处理
        } finally {
            cursor.close();
            db.close();
        }
        return result;
    }

    @SuppressLint("Range")
    public List<CirclePost> getCirclePostsByUserNumber(String userNumber) {
        List<CirclePost> circlePostList = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME, null, COLUMN_NUMBER + "=?", new String[]{userNumber}, null, null, null);
        try {
            if (cursor.moveToFirst()) {
                do {
                    CirclePost circlePost = new CirclePost();
                    // 绑定查询到的数据到CirclePost对象
//                    circlePost.setId(cursor.getInt(cursor.getColumnIndex(COLUMN_ID)));
                    circlePost.setContent(cursor.getString(cursor.getColumnIndex(COLUMN_CONTENT)));
//                    circlePost.setImageUrl(cursor.getString(cursor.getColumnIndex(COLUMN_IMAGE_URL)));
                    circlePostList.add(circlePost);
                } while (cursor.moveToNext());
            }
        } finally {
            cursor.close();
            db.close();
        }
        return circlePostList;
    }

    // 其他数据库操作方法...
}